<template>
  <div v-if="isDataLoaded">
    <!-- 在数据加载完成后渲染表格 -->
    <h2 class="title">历史上的今天</h2>
    <el-table
      :data="computedTableData"
      style="width: 100%"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="date" label="日期" width="180"> </el-table-column>
      <el-table-column prop="name" label="事件" width="180"> </el-table-column>
      <el-table-column prop="desc" label="描述"> </el-table-column>
    </el-table>
  </div>
  <div v-else>数据加载中...</div>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";
import axios from "axios"; // 导入axios

const tableData = ref([]);
const isDataLoaded = ref(false); // 增加一个标志变量来跟踪数据加载状态

const getHistoryInfo = async () => {
  try {
    let { data } = await axios.get("https://api.leafone.cn/api/lishi");
    console.log(data);
    tableData.value = data.data.info.map((item) => ({
      date: item.time,
      name: item.title,
      desc: item.desc,
    }));
    // 数据加载完成后，等待下一帧再更新数据加载状态
    nextTick(() => {
      isDataLoaded.value = true;
    });
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

const tableRowClassName = ({ rowIndex }) => {
  if (rowIndex === 1) {
    return "warning-row";
  } else if (rowIndex === 3) {
    return "success-row";
  }
  return "";
};

// 将tableData转换为计算属性以便在模板中访问
const computedTableData = computed(() => tableData.value);

// 在函数内使用onMounted来执行获取数据的函数
const loadData = async () => {
  await getHistoryInfo();
};

loadData(); // 调用加载数据的函数
</script>

<style scoped>
.title {
  margin: 0 auto;
  text-align: center;
}

/* 样式部分保持不变 */
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
